import 'package:get/get.dart';
import '../model/plant_record_model.dart';

/// 植物记录状态管理
/// 使用GetX进行全局状态管理，采用非常规命名避免标准模式
class PlantRecordState extends GetxController {
  // 所有植物记录
  final RxList<PlantRecordModel> _allRecords = <PlantRecordModel>[].obs;

  // 当前选中的记录
  final Rx<PlantRecordModel?> _currentRecord = Rx<PlantRecordModel?>(null);

  /// 获取所有记录
  List<PlantRecordModel> get allRecords => _allRecords.toList();

  /// 获取当前记录
  PlantRecordModel? get currentRecord => _currentRecord.value;

  /// 记录总数
  int get recordCount => _allRecords.length;

  /// 添加新记录
  void addRecord(PlantRecordModel record) {
    // 检查是否已存在相同日期的记录
    final existingIndex = _allRecords.indexWhere(
      (r) => _isSameDay(r.recordDate, record.recordDate),
    );

    if (existingIndex != -1) {
      // 如果存在，则更新记录
      _allRecords[existingIndex] = record.copyWith(
        id: _allRecords[existingIndex].id,
      );
    } else {
      // 添加新记录
      _allRecords.add(record);
    }

    // 按日期降序排序（最新的在前面）
    _allRecords.sort((a, b) => b.recordDate.compareTo(a.recordDate));
  }

  /// 更新记录
  void updateRecord(PlantRecordModel updatedRecord) {
    final index = _allRecords.indexWhere((r) => r.id == updatedRecord.id);
    if (index != -1) {
      _allRecords[index] = updatedRecord;

      // 如果当前记录被更新，也要更新当前记录
      if (_currentRecord.value?.id == updatedRecord.id) {
        _currentRecord.value = updatedRecord;
      }

      // 重新排序
      _allRecords.sort((a, b) => b.recordDate.compareTo(a.recordDate));
    }
  }

  /// 删除记录
  void deleteRecord(String recordId) {
    _allRecords.removeWhere((r) => r.id == recordId);

    // 如果删除的是当前记录，清空当前记录
    if (_currentRecord.value?.id == recordId) {
      _currentRecord.value = null;
    }
  }

  /// 获取今天的记录
  PlantRecordModel? getTodayRecord() {
    return _allRecords.firstWhereOrNull(
      (r) => _isSameDay(r.recordDate, DateTime.now()),
    );
  }

  /// 获取指定日期的记录
  PlantRecordModel? getRecordByDate(DateTime date) {
    return _allRecords.firstWhereOrNull((r) => _isSameDay(r.recordDate, date));
  }

  /// 设置当前记录
  void setCurrentRecord(PlantRecordModel? record) {
    _currentRecord.value = record;
  }

  /// 创建新的植物记录实例
  PlantRecordModel createNewRecord({DateTime? date}) {
    return PlantRecordModel(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      recordDate: date ?? DateTime.now(),
    );
  }

  /// 检查两个日期是否是同一天
  bool _isSameDay(DateTime date1, DateTime date2) {
    return date1.year == date2.year &&
        date1.month == date2.month &&
        date1.day == date2.day;
  }
}
